<template>
  <div>
    <div class="pt-6 border-b ml-4">
      <div class="inline-block">
        <span class="text-lg">{{ article.title }}</span>
        <div class="text-xs text-gray-600 flex py-4">
          <div class="px-4">
            发布于<span class="text-black">{{
              $moment(article.created_at).fromNow()
            }}</span>
          </div>
          <div class="px-4">
            更新于<span class="text-black">{{
              $moment(article.updated_at).fromNow()
            }}</span>
          </div>
        </div>
      </div>
    </div>
    <div class="markdown-body">
      <div v-html="htms"></div>
    </div>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import showdown from "showdown";
import cheerio from "cheerio";
import hljs from "highlight.js";
import "github-markdown-css/github-markdown.css";
import "./styles.css";

const converter = new showdown.Converter();
converter.setOption("tables", true);

export default {
  name: "MdShower",
  props: {
    id: {},
  },
  computed: {
    ...mapGetters(["articles"]),
    article() {
      return this.articles.find((item) => item.number === this.id) || {};
    },
    htms() {
      let htmlStr = this.article.body
        ? converter.makeHtml(
            this.article.body.replace(
              new RegExp("https://images.gitee.com/uploads/images/", "g"),
              "/gitee/loadimage?path="
            )
          )
        : "";
      let $ = cheerio.load(htmlStr);
      let blocks = $("pre code");
      blocks.each((idx, block) => {
        let h = hljs.highlightAuto($(block).text()).value;
        $(block).empty().append(h);
        $(block).addClass("hljs");
      });

      return $.html();
    },
  },
  data() {
    return {
      isLoading: true,
    };
  },
  // created() {
  //   this.renderHtml();
  // },
  mounted() {
    console.log("just run client");
  },
  methods: {
    renderHtml() {
      this.isLoading = false;
      console.log(this.article.body);
      this.htms = converter.makeHtml(
        this.article.body &&
          this.article.body.replace(
            new RegExp("https://images.gitee.com/uploads/images/", "g"),
            "/gitee/loadimage?path="
          )
      );
      this.$nextTick(() => {
        this.isLoading = true;
      });
    },
  },
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
code {
  background: #eef1f6;
  padding: 15px 16px;
  margin-bottom: 20px;
  display: block;
  line-height: 36px;
  font-size: 15px;
  font-family: Source Sans Pro, Helvetica Neue, Arial, sans-serif;
}
.markdown-body {
  margin: 20px;
}
</style>